package com.kz.springboot.web.controller;

import com.github.pagehelper.PageInfo;
import com.kz.springboot.common.BaseResponseUtil;
import com.kz.springboot.common.response.BaseResponse;
import com.kz.springboot.model.BaseRole;
import com.kz.springboot.protocol.RoleInfoQueryParam;
import com.kz.springboot.service.RoleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user/roleInfo")
public class RoleController {


    @Autowired
    CacheManager cacheManager;

    @Autowired
    RoleInfoService roleInfoService;

    @PostMapping(value = "/save")
    public Object save(@RequestBody BaseRole entity) {
        int result = roleInfoService.save(entity);

        if (result > 0) {
            return new BaseResponse().successResponse("保存成功", entity.getId());
        } else {
            return new BaseResponse().errorResponse("保存失败");
        }
    }

    @GetMapping(value = "/{id}/detail")
    public Object detail(@PathVariable long id) {
        BaseRole entity = roleInfoService.getById(id);
        return BaseResponseUtil.constructResponse(BaseResponseUtil.SUCCESS, "查询成功", entity);
    }

    @PutMapping(value = "/update")
    public Object update(@RequestBody BaseRole entity) {
        int result = roleInfoService.update(entity);

        if (result > 0) {
            return BaseResponseUtil.constructResponse(BaseResponseUtil.SUCCESS, "修改成功", entity.getId());
        } else {
            return BaseResponseUtil.constructResponse(BaseResponseUtil.FAILED, "修改失败");
        }
    }

    @DeleteMapping(value = "/{id}")
    public Object remove(@PathVariable long id) {
        int result = roleInfoService.remove(id);

        if (result > 0) {
            return BaseResponseUtil.constructResponse(BaseResponseUtil.SUCCESS, "删除成功");
        } else {
            return BaseResponseUtil.constructResponse(BaseResponseUtil.FAILED, "删除失败");
        }
    }

    @GetMapping(value = "/list")
    public Object list(RoleInfoQueryParam queryParam) {
        PageInfo pageInfo = roleInfoService.pageQuery(queryParam);

        return BaseResponseUtil.constructResponse(BaseResponseUtil.SUCCESS, "查询成功", pageInfo);
    }


    private void setUserCache(String key) {
        Cache cache = cacheManager.getCache("cachename");
        cache.put(key, "1");
    }

    private String getUserCache(String key) {
        Cache cache = cacheManager.getCache("cachename");
        return cache.get(key).toString();
    }
}

